import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

// 定义一个异常过滤器，用于捕获HTTP异常
@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  // 捕获异常的方法
  catch(exception: HttpException, host: ArgumentsHost) {
    // 获取HTTP上下文
    const ctx = host.switchToHttp();
    // 获取响应对象
    const response = ctx.getResponse<Response>();
    // 获取请求对象
    const request = ctx.getRequest<Request>();
    // 获取异常状态码
    const status = exception.getStatus();

    // 获取异常信息
    const message = exception.message;

    // response
    response.status(status).json({
      status,
      time: new Date().toISOString(),
      data: {
        path: request.url,
        message,
      },
      success: false,
    });
  }
}
